package com.expand.learn.config;

import com.alibaba.fastjson.JSONObject;
import com.expand.learn.model.Person;
import org.springframework.http.HttpInputMessage;
import org.springframework.http.HttpOutputMessage;
import org.springframework.http.MediaType;
import org.springframework.http.converter.AbstractHttpMessageConverter;
import org.springframework.http.converter.HttpMessageNotReadableException;
import org.springframework.http.converter.HttpMessageNotWritableException;
import org.springframework.stereotype.Component;
import org.springframework.util.StreamUtils;

import java.io.IOException;
import java.nio.charset.Charset;

/**
 * @author zhanghaidong
 * @version v1.0
 * @description
 * @date 2020/2/27
 */
@Component
public class CustomizeHttpMessageConverter extends AbstractHttpMessageConverter<Person> {

    public CustomizeHttpMessageConverter() {
        super(new MediaType("application", "x-custom", Charset.forName("UTF-8")));
    }

    @Override
    protected boolean supports(Class<?> clazz) {
        return clazz.isAssignableFrom(Person.class);
    }

    @Override
    protected Person readInternal(Class<? extends Person> clazz, HttpInputMessage inputMessage) throws IOException, HttpMessageNotReadableException {
        System.out.println("---------CustomizeHttpMessageConverter--------------readInternal");
        String name = StreamUtils.copyToString(inputMessage.getBody(), Charset.forName("UTF-8"));
        return new Person(name, 88);
    }

    @Override
    protected void writeInternal(Person person, HttpOutputMessage outputMessage) throws IOException, HttpMessageNotWritableException {
        System.out.println("---------CustomizeHttpMessageConverter--------------writeInternal");
        outputMessage.getBody().write(JSONObject.toJSONBytes(person));
    }
}
